import { useAuthStore } from '@/store'
import { resolveResError } from '@/utils/http/helpers.js'

export function setupInterceptors(axiosInstance) {
  // 请求拦截器
  axiosInstance.interceptors.request.use(reqResolve, reqReject)
  // 响应拦截器
  axiosInstance.interceptors.response.use(resResolve, resReject)
}

function reqResolve(config) {
  // 处理不需要token的请求
  if (config.needToken === false) {
    return config
  }

  const { accessToken } = useAuthStore()
  if (accessToken) {
    config.Authorization = `Bearer ${accessToken}`
  }
  return config
}

function reqReject(error) {
  return Promise.reject(error)
}

function resResolve(response) {
  const { data, status, config, statusText, headers } = response
  if (headers['content-type']?.includes('json')) {
    if (data.success) {
      return Promise.resolve(data)
    }
    const code = data?.errCode ?? status
    const needTip = config?.needTip !== false
    // 根据code处理对应的操作，并返回处理后的message
    const message = resolveResError(code, data?.errMsg ?? statusText, needTip)
    return Promise.reject({ code, message, error: data ?? response })
  }
  return Promise.resolve(response)
}

async function resReject(error) {
  if (!error || !error.response) {
    const code = error?.code
    /** 根据code处理对应的操作，并返回处理后的message */
    const message = resolveResError(code, error.message)
    return Promise.reject({ code, message, error })
  }

  const { data, status, config } = error.response
  const code = data?.errCode ?? status

  const needTip = config?.needTip !== false
  const message = resolveResError(code, data?.errMsg ?? error.message, needTip)
  return Promise.reject({
    code,
    message,
    error: error.response?.data || error.response,
  })
}
